<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产ID" prop="assetId" >
        <el-input
          v-model="queryParams.assetId"
          placeholder="请输入资产ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报修人" prop="userId" >
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入报修人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="维修人员" prop="repairPerson" >
        <el-input
          v-model="queryParams.repairPerson"
          placeholder="请输入维修人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>-->
<!--          <el-option label="通过" value="通过" />-->
<!--          <el-option label="拒绝" value="拒绝" />-->
<!--          <el-option label="待审核" value="待审核" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="维修结果" prop="repairResult">
              <el-select v-model="queryParams.repairResult" placeholder="请选择维修结果" clearable>
                <el-option label="待维修" value="待维修" />
                <el-option label="维修中" value="维修中" />
              </el-select>
            </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['assets:repairAudit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairAuditList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="repairApplicationId" />
      <el-table-column label="资产ID" align="center" prop="assetId" width="180" />
      <el-table-column label="报修人" align="center" prop="userId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.userId] || scope.row.userId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="申请原因" align="center" prop="repairApplyReason" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            :style="{ backgroundColor: getStatusType(scope.row.status), color: 'white' }"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="adminId">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.adminId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="reviewTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修时间" align="center" prop="repairTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.repairTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修结果" align="center" prop="repairResult">
        <template slot-scope="scope">
          <el-tag
            :type="getRepairResultType(scope.row.repairResult)"
            :style="{ backgroundColor: getRepairResultColor(scope.row.repairResult), color: 'white' }"
          >
            {{ getRepairResultText(scope.row.repairResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="维修人" align="center" prop="repairPerson">
        <template slot-scope="scope">
          <span>{{ userMap[scope.row.repairPerson] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleApprove(scope.row)"
            v-if="scope.row.status === '待审核'"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleStartRepair(scope.row)"
            v-if="scope.row.status === '通过'"
          >开始维修</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleFinishRepair(scope.row)"
            v-if="scope.row.status === '通过'"
          >完成维修</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="确认维修结果" :visible.sync="finishRepairDialogVisible" width="600px" append-to-body>
      <el-form ref="finishRepairForm" :model="currentRepairAudit" :rules="finishRepairRules">
        <el-form-item label="维修结果" prop="repairResult">
          <el-radio-group v-model="selectedRepairResult">
            <el-radio label="已修复">已修复</el-radio>
            <el-radio label="维修失败">维修失败</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="维修报告" prop="repairReport">
<!--          &lt;!&ndash; 使用原生 textarea 标签 &ndash;&gt;-->
<!--          <textarea-->
<!--            v-model="repairReportText"-->
<!--            placeholder="请详细描述维修过程和结果"-->
<!--            rows="5"-->
<!--            style="width: 100%;"-->
<!--          ></textarea>-->
          <el-input v-model="currentRepairAudit.repairReport" type="textarea" placeholder="请输入维修描述：" />
        </el-form-item>
        <el-form-item label="维修附件">
          <el-upload
            class="upload-demo"
            action="#"
            :multiple="true"
            :file-list="uploadedFiles"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            accept="image/*, video/*"
          >
            <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">支持上传图片和视频文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="finishRepairDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFinishRepair">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="approveTitle" :visible.sync="approveDialogVisible" width="300px" append-to-body>
      <el-radio-group v-model="approveAction">
        <el-radio label="approve">通过</el-radio>
        <el-radio label="reject">拒绝</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApprove">确 定</el-button>
        <el-button @click="approveDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listRepairAudit, getRepairAudit, delRepairAudit, addRepairAudit, updateRepairAudit } from "@/api/assets/repairAudit";
import {parseTime} from "@/utils/ruoyi";
import {approveRepair, finishRepair, rejectRepair, startRepair} from "@/api/assets/repair";
import {listUser} from "@/api/system/user";

export default {
  name: "RepairAudit",
  data() {
    return {
      //审核对话框变量
      approveDialogVisible: false,
      approveTitle: "",
      approveAction: "approve",
      approveRepairAudit: null, // 存储整个 repairAudit 对象
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报修审核表格数据
      repairAuditList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetId: null,
        userId: null,
        // status: null,
        adminId: null,
        repairPerson: null,
        // repairResult: null,
      },
      // 表单参数
      form: {
        repairApplicationId: null,
        assetId: null,
        userId: null,
        repairApplyReason: null,
        applyTime: null,
        status: null,
        adminId: null,
        reviewTime: null,
        repairTime: null,
        repairResult: null,
        repairPerson: null,
        repairReport: null
      },
      // 表单校验
      rules: {
        assetId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        applyTime: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      },
      // 用户信息缓存
      userMap: {},
      // 完成维修对话框变量
      finishRepairDialogVisible: false,
      selectedRepairResult: null,
      currentRepairAudit: null,
      // 新增的维修报告相关变量
      // repairReportText: '',
      uploadedFiles: [],
      finishRepairRules: {
        repairResult: [{ required: true, message: '请选择维修结果', trigger: 'change' }],
        repairReport: [{ required: true, message: '维修报告不能为空', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.getList();
    this.getUserList();
    // 初始化维修报告字段
    this.currentRepairAudit = { repairReport: '' };
  },
  methods: {
    parseTime,
    /** 查询报修审核列表 */
    getList() {
      this.loading = true;
      listRepairAudit(this.queryParams).then(response => {
        const filteredRows = response.rows.filter(row => {
          return (
            row.status === '待审核' ||
            (row.status === '通过' && (row.repairResult === '待维修' || row.repairResult === '维修中'))
          );
        });
        this.repairAuditList = filteredRows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUserList() {
      listUser().then(response => {
        this.userMap = response.rows.reduce((map, user) => {
          map[user.userId] = user.userName;
          return map;
        }, {});
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        repairApplicationId: null,
        assetId: null,
        userId: null,
        repairApplyReason: null,
        applyTime: null,
        status: null,
        adminId: null,
        reviewTime: null,
        repairTime: null,
        repairResult: null,
        repairPerson: null,
        repairReport: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.repairApplicationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报修审核";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const repairApplicationId = row.repairApplicationId || this.ids
      getRepairAudit(repairApplicationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报修审核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.repairApplicationId != null) {
            updateRepairAudit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRepairAudit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const repairApplicationIds = row.repairApplicationId || this.ids;
      this.$modal.confirm('是否确认删除报修审核编号为"' + repairApplicationIds + '"的数据项？').then(function() {
        return delRepairAudit(repairApplicationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('assets/repairAudit/export', {
        ...this.queryParams
      }, `repairAudit_${new Date().getTime()}.xlsx`)
    },
    /** 审核按钮操作 */
    handleApprove(row) {
      if (row.status === "通过") {
        this.$modal.msgWarning("该记录已审核通过，无法再次审核。");
        return;
      } else if (row.status === "拒绝") {
        this.$modal.msgWarning("该记录已审核拒绝，无法再次审核。");
        return;
      }
      this.approveRepairAudit = { ...row }; // 复制整个 row 对象
      this.approveTitle = "审核编号为'" + row.borrowLogId + "'的借用请求";
      this.approveDialogVisible = true;
    },
    /** 提交审核操作 */
    submitApprove() {
      if (this.approveAction === "approve") {
        this.approveBorrowRequest(this.approveRepairAudit);
      } else if (this.approveAction === "reject") {
        this.rejectBorrowRequest(this.approveRepairAudit);
      }
      this.approveDialogVisible = false;
    },
    /** 审核通过操作 */
    approveBorrowRequest(repairAudit) {
      this.$modal.confirm('是否确认通过编号为"' + repairAudit.repairApplicationId + '"的借用请求？').then(() => {
        approveRepair(repairAudit).then(response => {
          this.$modal.msgSuccess("审核通过");
          this.getList();
        });
      }).catch(() => {});
    },

    /** 审核拒绝操作 */
    rejectBorrowRequest(repairAudit) {
      this.$modal.confirm('是否确认拒绝编号为"' + repairAudit.repairApplicationId + '"的借用请求？').then(() => {
        rejectRepair(repairAudit).then(response => {
          this.$modal.msgSuccess("审核拒绝");
          this.getList();
        });
      }).catch(() => {});
    },
    getStatusText(status) {
      switch (status) {
        case "通过":
          return '通过';
        case "拒绝":
          return '拒绝';
        case "待审核":
          return '待审核';
        default:
          return '未知状态';
      }
    },
    getStatusType(status) {
      switch (status) {
        case "通过":
          return 'green'; // 通过状态使用绿色标签
        case "拒绝":
          return 'red'; // 拒绝状态使用红色标签
        case "待审核":
          return '#FFD700'; // 待审核状态使用黄色标签
      }
    },

    getRepairResultText(repairResult) {
      switch (repairResult) {
        case "待维修":
          return '待维修';
        case "维修中":
          return '维修中';
        case "已修复":
          return '已修复';
        case "维修失败":
          return '维修失败';
        default:
          return 'null';
      }
    },
    getRepairResultType(repairResult) {
      switch (repairResult) {
        case "待维修":
          return '#FFD700'; // 待维修状态使用黄色标签
        case "维修中":
          return 'blue'; // 报修中状态使用蓝色标签
        case "已修复":
          return 'green'; // 已修复状态使用绿色标签
        case "维修失败":
          return 'red'; // 维修失败状态使用红色标签
        default:
          return 'grey'; // 默认状态使用灰色标签
      }
    },
    getRepairResultColor(repairResult) {
      switch (repairResult) {
        case "待维修":
          return '#FFD700'; // 待维修状态使用黄色标签
        case "维修中":
          return 'blue'; // 报修中状态使用蓝色标签
        case "已修复":
          return 'green'; // 已修复状态使用绿色标签
        case "维修失败":
          return 'red'; // 维修失败状态使用红色标签
        default:
          return 'grey'; // 默认状态使用灰色标签
      }
    },
    /** 开始维修按钮操作 */
    handleStartRepair(repairAudit) {

      if (repairAudit.repairResult === "维修中" || repairAudit.repairResult === "已修复" || repairAudit.repairResult === "维修失败") {
        this.$modal.msgWarning("该设备已维修，请勿重复点击");
        return;
      }

      this.$modal.confirm('是否确认开始维修编号为"' + repairAudit.repairApplicationId + '"的报修请求？').then(() => {
        startRepair(repairAudit).then(response => {
          this.$modal.msgSuccess("开始维修成功");
          this.getList();
        });
      }).catch(() => {});

    },

    /** 完成维修按钮操作 */
    handleFinishRepair(repairAudit) {
      if (repairAudit.repairResult !== "维修中") {
        this.$modal.msgWarning("当前不能进行完成维修操作");
        return;
      }
      this.currentRepairAudit = { ...repairAudit,repairReport: ''}; // 复制整个 repairAudit 对象
      this.finishRepairDialogVisible = true;
    },
    /** 提交完成维修操作 */
    submitFinishRepair() {
      this.$refs.finishRepairForm.validate(valid => {
        if (valid) {
          this.currentRepairAudit.repairResult = this.selectedRepairResult;

          finishRepair(this.currentRepairAudit).then(response => {
            this.$modal.msgSuccess("维修报告提交成功");
            this.finishRepairDialogVisible = false;
            this.getList();
          });
        }
      });
    },
    handlePreview(file) {
      // 这里可以添加文件预览逻辑
      console.log('预览文件:', file);
    },

    handleRemove(file, fileList) {
      // 这里可以添加文件移除逻辑
      console.log('移除文件:', file, fileList);
    }


  }
};
</script>
